package com.mindcraft.shop.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mindcraft.base.model.MindCraftResult;
import com.mindcraft.base.utils.CommonConst;
import com.mindcraft.base.utils.JwtHelper;
import com.mindcraft.shop.client.UserClient;
import com.mindcraft.shop.dto.MarketDetailSkuComment;
import com.mindcraft.shop.dto.MarketSkuCommentDto;
import com.mindcraft.shop.mapper.MarketSkuCommentMapper;
import com.mindcraft.shop.po.MarketSkuComment;
import com.mindcraft.shop.service.MarketSkuCommentService;
import com.mindcraft.user.po.McUser;
import com.mindcraft.user.utils.MindCraftUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Slf4j
@Service
public class MarketSkuCommentServiceImpl extends ServiceImpl<MarketSkuCommentMapper, MarketSkuComment> implements MarketSkuCommentService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private MarketSkuCommentMapper marketSkuCommentMapper;

    @Override
    public MindCraftResult getSkuCommentSkuList(MarketSkuCommentDto marketSkuCommentDto) {

        lambdaQuery()
                .eq(MarketSkuComment::getSkuId, marketSkuCommentDto.getSkuId())
                .orderByDesc(MarketSkuComment::getCreateTime)
                .page(marketSkuCommentDto);

        List<MarketSkuComment> marketSkuCommentList = marketSkuCommentDto.getRecords();

        if (!CollectionUtils.isEmpty(marketSkuCommentList)) {
            marketSkuCommentList.stream().forEach((marketSkuComment -> {

                //封装用户信息
                McUser user = userClient.getUser(marketSkuComment.getUserId());
                marketSkuComment.setPhotoUrl(user.getUserpic());
                marketSkuComment.setNickName(user.getNickname());


            }));


        }


        return MindCraftResult.success(marketSkuCommentDto);

    }

    @Override
    public MindCraftResult CommentInsertAndgetId(MarketDetailSkuComment marketDetailSkuComment) {

        String token = MindCraftUtil.getRequest().getHeader(CommonConst.TOKEN);
        String userId = JwtHelper.getUserId(token);


        MarketSkuComment marketSkuComment = new MarketSkuComment();
        marketSkuComment.setContent(marketDetailSkuComment.getContent());
        //TODO 设置定位地址
        marketSkuComment.setIpAddr("未知");
        marketSkuComment.setUserId(userId);
        marketSkuComment.setSkuId(marketDetailSkuComment.getSkuId());

        int count = marketSkuCommentMapper.commentInsertAndgetId(marketSkuComment);
        if (count == 1) {
            int commentId = marketSkuComment.getId();
            return MindCraftResult.success(commentId);
        }else{
            return MindCraftResult.fail("插入失败");
        }
    }
}
